<template>
  <el-dialog
    title="新增"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="400px">
    <el-form
      ref="dataForm"
      :model="dataForm"
      label-width="100px">
      <el-form-item label="hs编码" prop="hsCode">
        <el-autocomplete
          popper-class="my-autocomplete"
          v-model="hsCode"
          value-key="goodsName"
          :fetch-suggestions="querySearch"
          placeholder="hs编码"
          :trigger-on-focus="false"
          @focus="handleFocus"
          @select="handleSelect"
          style="width: 80%;">

          <template slot-scope="{ item }">
            <div class="name">{{ item.goodsName }}</div>
            <span class="addr">{{ item.hsCode }}</span>
          </template>
        </el-autocomplete>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  // api
  import { addGoods, findByHsCode } from '@/api/dataAnalysis'

  export default {
    name: 'add-or-update',
    data() {
      return {
        visible: false,
        dataForm: {
          goodsId: '',
          goodsName: '',
          hsCode: ''
        },
        hsCode: ''
      }
    },
    methods: {
      init() {
        this.visible = true
        this.dataForm.goodsId = ''
        this.dataForm.goodsName = ''
        this.dataForm.hsCode = ''
        this.hsCode = ''
      },
      querySearch(queryString, cb) {
        findByHsCode({ hsCode: queryString }).then((res) => {
          const result = res.data.data
          cb(result)
        })
      },
      handleFocus(ev) {
        this.dataForm.goodsId = ''
        this.dataForm.goodsName = ''
        this.dataForm.hsCode = ''
      },
      handleSelect(item) {
        this.dataForm.goodsId = item.id
        this.dataForm.goodsName = item.goodsName
        this.dataForm.hsCode = item.hsCode
      },
      submitForm() {
        if (this.hsCode === '') {
          this.$message({
            message: 'hs编码不能为空',
            type: 'error'
          })
          return false
        }
        addGoods(this.dataForm).then((res) => {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.visible = false
          this.$emit('refresh')
        })
      },
      close() {
        this.visible = false
        this.$refs['dataForm'].resetFields()
      }
    }
  }
</script>


<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" rel="stylesheet/scss" type="text/scss">
  .my-autocomplete {
    li {
      line-height: normal;
      padding: 7px 20px;

      .name {
        text-overflow: ellipsis;
        overflow: hidden;
      }
      .addr {
        font-size: 12px;
        color: #b4b4b4;
      }

      .highlighted .addr {
        color: #ddd;
      }
    }
  }
</style>
